package com.lottery.shadowbd.utils;

import android.graphics.Bitmap;
import android.os.Environment;
import android.os.StatFs;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 文件Utils
 * Created by han on 2017/6/8 0008.
 */
public class FileUtil {

    /**
     * 判断SD卡上的文件夹是否存在
     */
    public static boolean isFileExist( String fileName) {
        if (!hasSdcard() && !checkExternalStorageCanWrite()) {
            return false;
        }

        File file = new File(fileName);

        return file.exists();
    }

    /**
     * @param saveDir
     * @return
     * @throws IOException 判断下载目录是否存在, 不存在在创建
     */
    public static boolean isExistDir(String saveDir) {
        // 下载位置
        File downloadFile = new File(saveDir);

        //mkdir只能创建一个文件夹，切父文件夹必须存在才能创建成功
        //mkdirs创建文件夹（可以创建多级）
        //createNewFile创建文件
        if (!downloadFile.exists()) {
            return downloadFile.mkdirs();
        }

        String savePath = downloadFile.getAbsolutePath();

        LogUtils.e("savePath===" + savePath);

        return true;
    }

    /**
     * 删除文件
     *
     * @param dirName
     * @return
     */
    public static boolean deleteFile(String dirName) {
        if (!hasSdcard() && !checkExternalStorageCanWrite()) {
            return false;
        }

        File dir = new File(dirName);

        if (dir.exists()) {
            return dir.delete();
        }

        return false;
    }

    public static void deleteAllFiles(File root) {
        if (!hasSdcard() && !checkExternalStorageCanWrite()) {
            return;
        }

        File files[] = root.listFiles();

        if (files != null)
            for (File f : files) {
                if (f.isDirectory()) { // 判断是否为文件夹
                    deleteAllFiles(f);
                    try {
                        f.delete();
                    } catch (Exception e) {
                    }
                } else {
                    if (f.exists()) { // 判断是否存在
                        deleteAllFiles(f);
                        try {
                            f.delete();
                        } catch (Exception e) {
                        }
                    }
                }
            }
    }

    /**
     * 获取SD卡总容量
     * @return
     */
    public static long getSDAllSize(){
        //取得SD卡文件路径
        File path = Environment.getExternalStorageDirectory();
        StatFs sf = new StatFs(path.getPath());
        //获取单个数据块的大小(Byte)
        long blockSize = sf.getBlockSize();
        //获取所有数据块数
        long allBlocks = sf.getBlockCount();
        //返回SD卡大小
        //return allBlocks * blockSize; //单位Byte
        //return (allBlocks * blockSize)/1024; //单位KB
        return (allBlocks * blockSize)/1024/1024; //单位MB
    }

    /**
     * 获取SD卡剩余空间
     * @return
     */
    public static long getSDFreeSize(){
        //取得SD卡文件路径
        File path = Environment.getExternalStorageDirectory();
        StatFs sf = new StatFs(path.getPath());
        //获取单个数据块的大小(Byte)
        long blockSize = sf.getBlockSize();
        //空闲的数据块的数量
        long freeBlocks = sf.getAvailableBlocks();
        //返回SD卡空闲大小
        //return freeBlocks * blockSize;  //单位Byte
        //return (freeBlocks * blockSize)/1024;   //单位KB
        return (freeBlocks * blockSize)/1024 /1024; //单位MB
    }

    /**
     * 检查SDCARD是否可写
     *
     * @return
     */
    public static boolean checkExternalStorageCanWrite() {
        try {
            boolean mouted = Environment.getExternalStorageState().equals(
                    Environment.MEDIA_MOUNTED);
            if (mouted) {
                boolean canWrite = new File(Environment
                        .getExternalStorageDirectory().getPath())
                        .canWrite();
                if (canWrite) {
                    return true;
                }
            }
        } catch (Exception e) {
        }
        return false;
    }

    /**
     * 保存图片
     *
     * @param path
     * @param name
     * @param bitmap
     */
    public static String writeBitmap(String path, String name, Bitmap bitmap) {
        File file = new File(path);

        if (!file.exists()) {
            file.mkdirs();
        }

        StringBuilder stringBuilder = new StringBuilder(path);
        stringBuilder.append("/");
        stringBuilder.append(name);

        File _file = new File(stringBuilder.toString());

        if (_file.exists()) {
            _file.delete();
        }

        FileOutputStream fos = null;

        try {
            fos = new FileOutputStream(_file);
            if (name != null && !"".equals(name)) {
                int index = name.lastIndexOf(".");
                if (index != -1 && (index + 1) < name.length()) {
                    String extension = name.substring(index + 1).toLowerCase();
                    if ("png".equals(extension)) {
                        bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
                    } else if ("jpg".equals(extension)
                            || "jpeg".equals(extension)) {
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 75, fos);
                    }
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return _file.getAbsolutePath();
    }

    /**
     * 检查sdk是否存在
     *
     * @return
     */
    public static boolean hasSdcard() {
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            return true;
        } else {
            return false;
        }
    }
}
